﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Transactions;

namespace Windows.Api.Share
{
    public class TransactionFilterAttribute : TypeFilterAttribute
    {
        public TransactionFilterAttribute() : base(typeof(TransactionActionFilter))
        {
        }
        public class TransactionActionFilter : IActionFilter
        {
            private TransactionScope? _transactionScope = null;
            public void OnActionExecuting(ActionExecutingContext context)
            {
                _transactionScope = new TransactionScope();
            }
            public void OnActionExecuted(ActionExecutedContext context)
            {
                if (context.Exception == null)
                {
                    _transactionScope?.Complete();
                }
                _transactionScope?.Dispose();
            }
        }
    }
}
